﻿
using B.S.DataBase.MyProject.ErrorCode;
using D.Traceability.Domain;
using D.Traceability.Infrastructure.Infrastructure;
using D.Traceability.Read.API.APPlicant.Command;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace D.Traceability.Read.API.APPlicant.CommandHandler
{
    /// <summary>
    /// 溯源管理列表
    /// </summary>
    public class ListTraceaCommandHandler : IRequestHandler<ListTraceaCommand, APIPaing<SU_TraceabilityModel>>
    {
        private readonly IBaseRepository<SU_TraceabilityModel> repository;

        public ListTraceaCommandHandler(IBaseRepository<SU_TraceabilityModel> repository)
        {
            this.repository = repository;
        }

        /// <summary>
        /// 显示溯源管理列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIPaing<SU_TraceabilityModel>> Handle(ListTraceaCommand request, CancellationToken cancellationToken)
        {
            APIPaing<SU_TraceabilityModel> paing = new APIPaing<SU_TraceabilityModel>();
            //查询所有(显示 未删除 状态 )
            var list = await repository.GetAll().Result.Where(x=>x.TraceaIsNo == false && x.TraceaIsDelete == false).ToListAsync();
            
            //条件



            int ToCount = list.Count();
            int ToPage = (int)Math.Ceiling(ToCount * 1.0 / request.ToSize);
            //分页
            list = list.OrderByDescending(x => x.TraceaId).Skip((request.ToIndex - 1) * request.ToSize).Take(request.ToSize).ToList();

            paing.Code = APIEnum.查询成功;
            paing.Msg = $"查询到{ToCount}条数据";
            paing.TotalCount = ToCount;
            paing.TotalPage = ToPage;
            paing.Items = list;
            return await Task.FromResult(paing);
        }
    }
}
